<script setup>
import { defineProps, defineEmits, onUpdated, reactive } from 'vue';
import { ElTable, ElTableColumn, ElDialog, ElButton, ElForm, ElFormItem, ElInput, ElInputNumber } from 'element-plus';
// import UserForm from "@/components/user/UserForm.vue";

const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  formDialog: {
    type: Object,
    default: () => ({
      dialogVisible: false,
      dialogTitle: '',
    })
  },
  formData: {
    type: Object,
    default: () => ({
      name: '',
      age: 0
    })
  }
})
const emit = defineEmits(['submitItem', 'deleteItem', 'updateFormData', 'updateDialogData'])

onUpdated(() => {
  console.log('onUpdated', props.formDialog, props.formData)
})

// 点击编辑按钮
const handleEdit = (row) => {
  console.log(row, props.formDialog)
  form.name = row = row.name
  form.age = row.age
  form.id = row.id
  emit('updateFormData', form)
  emit('updateDialogData', {
    ...props.formDialog,
    dialogVisible: true,
    dialogTitle: '编辑',
  })
}
// 点击删除按钮
const handleDelete = (id) => {
  emit('deleteItem', id)
}
// 关闭弹窗
const handleDialogClose = () => {
  emit('updateDialogData', {
    ...props.formDialog,
    dialogVisible: false,
    dialogTitle: '',
  })
}
// 提交表单
const onSubmit = () => {
  emit('submitItem');
}
// 更新表单字段
const updateField = (field, value) => {
  console.log(field, value);
  let formData = { ...props.formData };
  formData[field] = value;
  emit('updateFormData', formData);
};
</script>

<template>
  <div v-show="list.length">
    <el-table :data="list" style="width: 100%" stripe>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog v-model="formDialog.dialogVisible" :title="formDialog.dialogTitle" width="50%" @close="handleDialogClose">
    <el-form>
      <el-form-item label="姓名">
        <el-input :value="formData.name" @input="updateField('name', $event)" />
      </el-form-item>

      <el-form-item label="年龄">
        <el-input-number :value="formData.age" @input="updateField('age', $event)" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped></style>